#include "storage/filecache.h"
#include <stdlib.h>
#include "utils/palloc.h"
#include "storage/shmem.h"


static HTAB *CacheRelHash;

Size FileCacheSize(void) {
	return mul_size(MAX_CACHE_RELATION, sizeof(RelFileNode) + sizeof(CachedRelInfo));
}

void
InitCacheRel(void)
{
	HASHCTL		info;
	long		init_table_size,
				max_table_size;
	info.keysize = sizeof(RelFileNode);
	info.entrysize = sizeof(CachedRelInfo);
	init_table_size = 100;
	max_table_size = MAX_CACHE_RELATION;
	CacheRelHash = ShmemInitHash("CacheRel",
									  init_table_size,
									  max_table_size,
									  &info,
									  HASH_ELEM | HASH_BLOBS);
}

CachedRelInfo *
SetupRelCache(const RelFileNode *reln, ForkNumber forkno, BlockNumber nblocks)
{

	CachedRelInfo *ri;
	bool found;


	ri = (CachedRelInfo *)
		hash_search(CacheRelHash, reln, HASH_ENTER, &found);

	if (!found)
	{
		for (int i = 0; i <= MAX_FORKNUM; ++i)
			ri->cached_nblocks[i] = InvalidBlockNumber;
        ri->cached_nblocks[forkno] = nblocks;
	}

	return ri;
}

void RemoveCacheRel(const RelFileNode *reln)
{

	hash_search(CacheRelHash, (const void *) reln,
						HASH_REMOVE, NULL);
}

CachedRelInfo *
FindCacheRel(const RelFileNode *reln)
{

	CachedRelInfo *ri;
	bool found;


	ri = (CachedRelInfo *)
		hash_search(CacheRelHash, reln, HASH_FIND, &found);

	return ri;
}
